import { React, createElement } from 'react';
import {
  BrowserRouter, Routes, Route, useNavigate 
} from 'react-router-dom';
import config from '../config/routers.config';

// import './router.css';

function GlobalPropsConfig({ title, children }) {
  const changeView = useNavigate();
  window.changeView = changeView;
  const globalProps = {
    changeView,
    title: title || ''
  };
  return createElement(children, { ...globalProps });
}

const getRouters = (routers = []) => (
// const urlManger = useNavigate();

  routers.map((item) => (
    <Route
        path={item.path || ''}
        redirectTo={item.redirectTo || false}
        key={item.name}
        index={item.index || false}
        element={<GlobalPropsConfig title={item.name}>{item.component || ''}</GlobalPropsConfig>}
    >
      {getRouters(item.children || [])}
    </Route>
  ))
);

function RouterEntrance() {
  // 设置index默认路由 就不能设置path 不然不会生效
  return (
    <BrowserRouter>
      <Routes>
        {getRouters(config)}
      </Routes>
    </BrowserRouter>
  );
}

export default RouterEntrance;
